import axios from 'axios';
import qs from 'qs';

// 动态设置 baseUrl 适应不同环境
const getBaseUrl = () => {
  const isElectron = navigator.userAgent.toLowerCase().includes('electron');

  if (process.env.NODE_ENV === 'development') {
    return '/api'; // 由 devServer 代理
  }

  if (isElectron) {
    return 'http://localhost:8000'; // 生产环境下拼接完整路径
  }

  return '/api'; // 普通 web 部署时，如 nginx 的 proxy
};

const baseUrl = getBaseUrl();

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: baseUrl,
  timeout: 30000,
  withCredentials: true,
  paramsSerializer: params => qs.stringify(params, { indices: false })
});

// 统一错误处理
const handleError = (error) => {
  const err = new Error();
  err.code = error.response?.status || 'NETWORK_ERROR';
  err.message = error.response?.data?.message || error.message || 'Network Error';
  err.data = error.response?.data;
  console.error(`API Error [${err.code}]:`, err.message);
  throw err; // 抛出错误让调用方捕获
};

// 替换 URL 路径参数
const replacePathParams = (url, params) => {
  return url.replace(/\{(\w+)}/g, (_, key) => {
    if (!params[key]) {
      console.warn(`Missing path parameter: ${key}`);
    }
    return params[key] || '';
  });
};

/**
 * GET 请求
 * @param {string} url - 可包含 {param} 占位符
 * @param {object} options - { pathParams, queryParams }
 */
const get = async (url, { pathParams = {}, queryParams = {} } = {}) => {
  try {
    const finalUrl = replacePathParams(url, pathParams);
    const response = await apiClient.get(finalUrl, { params: queryParams });
    return response.data;
  } catch (error) {
    return handleError(error);
  }
};

/**
 * POST 请求
 * @param {string} url
 * @param {object} options - { body, queryParams, headers }
 */
const post = async (url, { body = {}, queryParams = {}, headers = {} } = {}) => {
  try {
    const response = await apiClient.post(url, body, {
      params: queryParams,
      headers: {
        'Content-Type': 'application/json',
        ...headers
      }
    });
    return response.data;
  } catch (error) {
    return handleError(error);
  }
};

/**
 * PUT 请求
 * @param {string} url
 * @param {object} options - { body, queryParams, headers }
 */
const put = async (url, { body = {}, queryParams = {}, headers = {} } = {}) => {
  try {
    const response = await apiClient.put(url, body, {
      params: queryParams,
      headers: {
        'Content-Type': 'application/json',
        ...headers
      }
    });
    return response.data;
  } catch (error) {
    return handleError(error);
  }
};

/**
 * DELETE 请求
 * @param {string} url - 可包含 {param} 占位符
 * @param {object} options - { pathParams, queryParams }
 */
const remove = async (url, { pathParams = {}, queryParams = {} } = {}) => {
  try {
    const finalUrl = replacePathParams(url, pathParams);
    const response = await apiClient.delete(finalUrl, { params: queryParams });
    return response.data;
  } catch (error) {
    return handleError(error);
  }
};

/**
 * 上传文件 (FormData)
 * @param {string} url
 * @param {FormData} formData
 * @param {object} options - { onUploadProgress, headers }
 */
const upload = async (url, formData, { onUploadProgress, headers = {} } = {}) => {
  try {
    const response = await apiClient.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        ...headers
      },
      onUploadProgress
    });
    return response.data;
  } catch (error) {
    return handleError(error);
  }
};

export default {
  get,
  post,
  put,
  remove,
  upload,
  // 暴露 baseUrl 供需要直接使用的场景
  getBaseUrl: () => baseUrl
}
